package cn.uway.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.uway.utils.JSONUtils;
import cn.uway.utils.MD5Encoder;
import cn.uway.utils.PubValue;
import cn.uway.utils.WebUtils;

public class AuthInterceptor extends HandlerInterceptorAdapter {

	protected  Logger log = LoggerFactory.getLogger(this.getClass());
	
	private String loginUrl;
	
	public AuthInterceptor(){
		
	}
	
    public AuthInterceptor(String loginUrl){
		this.loginUrl = loginUrl;
	}
	
	@Override    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        
		String requestUri = request.getRequestURI();  
        String contextPath = request.getContextPath();  
        String url = requestUri.substring(contextPath.length());  
        
        log.debug("========requestUri={}, contextPath={}, url={}", requestUri, contextPath, url);     
        
        if(url.startsWith("/login") || url.startsWith("/ajax/login")){
        	return true;
        }
        String userId = request.getParameter("userId");
        String loginId = request.getParameter("loginId"); //登录获得的TOKEN
        boolean flag = true;
        String msg = "";
        if( StringUtils.isEmpty(loginId) && !StringUtils.isEmpty(userId) ){
        	loginId = MD5Encoder.encode(userId);
        }
        if( StringUtils.isEmpty(loginId) ){
        	flag = false;
        	msg = "参数loginId或userId不能为空";
        }
        if(flag){
        	String savedLoginId = (String)request.getSession().getAttribute(PubValue.SESSIONKEY_LOGIN_ID);
        	if(savedLoginId==null || (savedLoginId!=null && !savedLoginId.equals(loginId) ) ){
        		msg = "您已被踢下线，请重新登录";
        		flag = false;
        	}
        }
        if(flag){
        	return true;
        }
        else{
        	if(WebUtils.isAjax(request)){
         		 Map<String,String> resultMap =  new HashMap<String,String>();
         		 resultMap.put(PubValue.RET_CODE_KEY, PubValue.RET_CODE_FAILED);
         		 resultMap.put(PubValue.RET_MSG_KEY, msg);
         		 writeToPage(JSONUtils.toJson(resultMap), response);
          		 return false;
            }
	       	else{
	       		System.out.println("===============loginId 不匹配， forward, url ="+loginUrl);
	       		request.getRequestDispatcher(loginUrl).forward(request, response);
	       		return false;
	       	}
        }        
    }   
    
    public void writeToPage(String content, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "text/html;charset=UTF-8");
		PrintWriter pw = null;		
		try {
			pw = response.getWriter();
			pw.write(content);
		} 
		catch (IOException e) {
			log.warn("write to page error: ", e);
		} finally {
			if (pw != null) {
				pw.flush();
				pw.close();
			}
		}
	}  	 
    
    
}
